﻿using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface;
using ZilLion.Service.WeChatMall.Domain.Responses;
using ZilLion.Service.WeChatMall.Domain.Services.Interface;
using Microsoft.AspNetCore.HttpOverrides;
namespace ZilLion.Service.WeChatMall.Controllers
{
    /// <summary>
    ///     微商城高德地图对接
    /// </summary>
    [Route("Api/WechatMall/Map")]
   
    public class GpsMapController : WechatMallControllerBase
    {
        private readonly IAppInfoService _appInfoService;
        private readonly IShopInfoService _shopInfoService;

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="gdMapRepository"></param>
        /// <param name="appInfoService"></param>
        /// <param name="shopInfoService"></param>
        public GpsMapController(IGdMapRepository gdMapRepository, IAppInfoService appInfoService,
            IShopInfoService shopInfoService)
        {
            _gdMapRepository = gdMapRepository;
            _appInfoService = appInfoService;
            _shopInfoService = shopInfoService;
        }

        #region 获取城市列表

        /// <summary>
        ///     获取客户端IP和地址信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetAllCitys")]
        [HttpGet]
        public MapCitysResponse GetAllCitys(string token = null)
        {
            var result = new MapCitysResponse {MapCategorys = new List<MapCategoryDto>()};
            var dtos = _gdMapRepository.GetAllCitys();

            if (dtos.Status != "1") return result;
            var provinces = dtos?.Subdistricts?.FirstOrDefault()?.Subdistricts;
            var order = 1;
            foreach (var province in provinces ?? new List<MapDistrict>())
            {
                var wechatMallCategoryDto = new MapCategoryDto {Name = province.Name, Order = order};
                var list = province.Subdistricts.ToList();
                wechatMallCategoryDto.Citys = list;
                result.MapCategorys.Add(wechatMallCategoryDto);
                order++;
            }
            return result;
        }

        #endregion

        #region 根据关键词搜索

        /// <summary>
        ///     根据关键字和城市编码获取模糊匹配的地址
        /// </summary>
        /// <param name="citycode"></param>
        /// <param name="token"></param>
        /// <param name="keywords"></param>
        /// <returns></returns>
        [Route("SerchByKeywords")]
        [HttpGet]
        public MapSerchResponse SerchByKeywords(string keywords, string citycode = null, string token = null)
        {
            var tmp = _gdMapRepository.SerchMap(citycode, keywords);
            foreach (var tip in tmp.Tips)
            {
                if (tip.Address == null || tip.Address.ToString() == "[]")
                    tip.Address = string.Empty;
                if (tip.Id == null || tip.Id.ToString() == "[]")
                    tip.Id = string.Empty;

                if (tip.Location == null || tip.Location.ToString() == "[]")
                    tip.Location = string.Empty;
            }
            return tmp;
        }

        #endregion

        #region 判断两个坐标之间最短距离(单位:米)

        /// <summary>
        ///     判断两个坐标之间最短距离(单位:米)
        /// </summary>
        /// <param name="sourceLocation"></param>
        /// <param name="targetLocation"></param>
        /// <param name="adcode"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("CheckSendRange")]
        [HttpGet]
        public CheckSendRangeResponse CheckSendRange(string sourceLocation, string targetLocation,
            string adcode,
            string token = null)
        {
            var appid = GetAppId();
            var appinfo = _appInfoService.GetAppByAppId(appid);
            if (appinfo.AppBasicInfo.AppHomeType == 1)
            {
                var shops = _shopInfoService.GetShopsByAppid(appid)
                    .Where(x => x.Adcode.ToString().Left(4) == adcode.Left(4) && x.IsSendCenter).ToList();
                var lockobj = new object();
                var findInRange = false;
                Parallel.ForEach(shops, shop =>
                {
                    var dto = _gdMapRepository.GetShortestPath(shop.Location, targetLocation);
                    var path = dto?.Route?.Paths.FirstOrDefault();
                    if (path == null || path.Distance.ToLong() > appinfo.AppBasicInfo.SendRange * 1000)
                        return;
                    lock (lockobj)
                    {
                        findInRange = true;
                    }
                });
                return new CheckSendRangeResponse
                {
                    IsInRange = findInRange
                };
            }
            {
                var dto = _gdMapRepository.GetShortestPath(sourceLocation, targetLocation);
                var path = dto?.Route?.Paths.FirstOrDefault();
                if (path != null)
                    return new CheckSendRangeResponse
                    {
                        IsInRange = path.Distance.ToLong() <= appinfo.AppBasicInfo.SendRange * 1000
                    };
            }
            // 如果找不到路径 返回一个超范围的结果
            return new CheckSendRangeResponse {IsInRange = false};
        }

        #endregion

        #region 获取客户端城市

        private const string HttpContext = "MS_HttpContext";

        private const string RemoteEndpointMessage =
            "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

        private const string OwinContext = "MS_OwinContext";
        private readonly IGdMapRepository _gdMapRepository;

        /// <summary>
        ///     获取客户端IP和地址信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetRemoteCity")]
        [HttpGet]
        public RemoteCityResponse GetRemoteCity(string token = null)
        {
            var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            var result = _gdMapRepository.GetCityInfoByIp(ip);
            if (result != null && result.Status != "0")
            {
                result.IpAddress = ip;
                if (result.Adcode != "320000")
                    return new RemoteCityResponse
                    {
                        Name = result.City,
                        Adcode = result.Adcode,
                        Center = string.Empty
                    };
            }
            var appid = GetAppId();
            if (appid.IsNotNullOrEmpty())
            {
                var appinfo = _appInfoService.GetAppByAppId(appid);
                if (appinfo != null)
                    return new RemoteCityResponse
                    {
                        Name = appinfo.AppBasicInfo.CityName,
                        Adcode = appinfo.AppBasicInfo.CityAdcode,
                        Center = appinfo.AppBasicInfo.CityCenter
                    };
            }
            //返回默认地址 :南京
            return new RemoteCityResponse
            {
                Name = "南京市",
                Adcode = "320100",
                Center = string.Empty
            };
        }

      

        #endregion
    }
}